<template>
  <div>
    <div>
      <Card title="新增品牌" :bordered="false" dis-hover class="ivu-mt">
        <Form
          ref="brandForm"
          :model="brandFormData"
          :rules="brandFormRules"
          :label-width="140"
        >
          <Row>
            <Col span="18" offset="3">
              <FormItem label="品牌名称：" prop="brandName">
                <Input
                  v-model.trim="brandFormData.brandName"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入品牌名称"
                ></Input>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="品牌英文名称：" prop="brandEnName">
                <Input
                  v-model="brandFormData.brandEnName"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入品牌英文名称"
                  @keyup.native="keyupNative('brandEnName')"
                ></Input>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="厂家品牌中文名：" prop="factoryBrandName">
                <Input
                  v-model.trim="brandFormData.factoryBrandName"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入品牌名称"
                ></Input>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="厂家品牌英文名：" prop="factoryBrandEnName">
                <Input
                  v-model="brandFormData.factoryBrandEnName"
                  maxlength="20"
                  show-word-limit
                  placeholder="请输入品牌英文名称"
                  @keyup.native="keyupNative('factoryBrandEnName')"
                ></Input>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="档次定位(内部)：">
                <Select
                  v-model="brandFormData.insideLevel"
                  style="width: 200px"
                >
                  <Option
                    v-for="(item, index) in levelMap"
                    :value="item.value"
                    :key="index"
                    >{{ item.label }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="档次定位(外部)：">
                <Select
                  v-model="brandFormData.outsideLevel"
                  style="width: 200px"
                >
                  <Option
                    v-for="(item, index) in levelMap"
                    :value="item.value"
                    :key="index"
                    >{{ item.label }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="系列：">
                <Row
                  justify="start"
                  v-for="(item, index) in serieList"
                  :key="index"
                >
                  <Col span="12">
                    <Col>{{ item }}</Col>
                  </Col>
                  <Col span="2">
                    <div @click="clickSerie(index)">
                      <Col>
                        <Icon color="red" type="md-close" />
                      </Col>
                    </div>
                  </Col>
                </Row>
                <Input
                  v-model.trim="newSerie"
                  placeholder="请输入系列名称"
                  style="width: 150px"
                  maxlength="25"
                />
                <Button
                  type="primary"
                  @click="addSerieList"
                  style="margin-left: 10px"
                  >添加</Button
                >
                <!-- <Input v-model="brandFormData.series" placeholder="请输入系列名称，多个使用英文逗号隔开" /> -->
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="主品牌：">
                <Input
                  v-model="brandFormData.parentName"
                  placeholder="请选择品牌"
                  :data="brandNameData"
                  @on-search="brandChange"
                  @on-blur="brandChangeBlurFun"
                  readonly
                  style="width: 200px"
                />
                <Button
                  icon="ios-search"
                  style="margin-right: 50px"
                  @click="searchBrandFun"
                />
                <!-- <Select v-model="brandFormData.parentUuid" style="width:200px">
                            <Option v-for="(item,index) in allBrandData" :value="item.uuid" :key="index">{{
                                item.brandName }}</Option>
                        </Select> -->
              </FormItem>
              <FormItem label="状态：">
                <RadioGroup v-model="brandFormData.brandState">
                  <Radio label="1">启用</Radio>
                  <Radio label="2">禁用</Radio>
                </RadioGroup>
              </FormItem>
              <FormItem label="厂家品牌影响力是否大于商品品牌：">
                <RadioGroup v-model="brandFormData.factoryInfluenceMore">
                  <Radio label="1">是</Radio>
                  <Radio label="2">否</Radio>
                </RadioGroup>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="长方形图：" prop="imageKey2">
                <Upload
                  class="ivu-mr qw-disflex"
                  :defaultList="brandImageKey2"
                  :mr="16"
                  :maxSize="2048"
                  :maxLen="1"
                  :format="['jpg', 'jpeg', 'png']"
                  @handleChangeImage="changeImageKey2"
                >
                </Upload>
                <p>提示: 上传图片大小不能超过2048K,尺寸750px*360px</p>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="正方形图：" prop="imageKey1">
                <Upload
                  class="ivu-mr qw-disflex"
                  :defaultList="brandImageKey1"
                  :mr="16"
                  :maxSize="2048"
                  :maxLen="1"
                  :format="['jpg', 'jpeg', 'png']"
                  @handleChangeImage="changeImageKey1"
                >
                </Upload>
                <p>提示: 上传图片大小不能超过2048K,尺寸100px*100px，比例1:1</p>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="厂家Logo：" prop="factoryLogo">
                <Upload
                  class="ivu-mr qw-disflex"
                  :defaultList="brandImageKey3"
                  :mr="16"
                  :maxSize="2048"
                  :maxLen="1"
                  :format="['jpg', 'jpeg', 'png']"
                  @handleChangeImage="changeImageKey3"
                >
                </Upload>
                <p>提示: 上传图片大小不能超过2048K,尺寸100px*100px，比例1:1</p>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem label="品牌描述：">
                <Input
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 5 }"
                  maxlength="200"
                  show-word-limit
                  v-model="brandFormData.note"
                  placeholder="请输入品牌描述"
                ></Input>
              </FormItem>
            </Col>
            <Col span="18" offset="3">
              <FormItem>
                <Button
                  type="primary"
                  :loading="isLoading"
                  @click="handleSubmit()"
                  >提交</Button
                >
                <Button @click="handleReset('brandForm')" class="ivu-ml-8"
                  >取消</Button
                >
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Card>
    </div>
    <!-- 搜索品牌列表 -->
    <Modal v-model="searchBrandModal" title="选择品牌" width="70%">
      <Card dis-hover>
        <Row type="flex" justify="start" align="bottom">
          <Col style="margin-right: 40px">
            <span style="margin-right: 10px">品牌名称</span>
            <Input
              style="width: auto"
              v-model="brandNameModel"
              placeholder="请输入品牌名称"
            ></Input>
          </Col>
          <Col>
            <Button
              type="primary"
              style="margin-right: 10px"
              @click="linkBrandBt('1')"
              >查询</Button
            >
            <Button @click="linkBrandBt('0')">清空</Button>
          </Col>
        </Row>
      </Card>
      <Card dis-hover>
        <Row>
          <Table :columns="linkBrandCol" border :data="linkBrandData">
            <template slot-scope="{ row }" slot="factoryInfluenceMore">
              <span v-if="row.factoryInfluenceMore === '1'">大于品牌</span>
              <span v-if="row.factoryInfluenceMore === '2'">小于品牌</span>
            </template>
            <template slot-scope="{ row }" slot="action">
              <Button
                type="primary"
                size="small"
                style="margin: 3px 0"
                @click="selectBrandBt(row)"
                >选择</Button
              >
            </template>
          </Table>
          <div class="ivu-mt ivu-text-center">
            <Page
              :total="totalNum"
              transfer
              show-total
              show-sizer
              :current.sync="nowPage"
              @on-change="brandChange"
              @on-page-size-change="handleBrandChange($event)"
            />
          </div>
        </Row>
      </Card>
    </Modal>
  </div>
</template>
<script>
import brandUpdata from './configjs/brandUpdata';
import Upload from '@/components/common/upload'; // 上传组件
import { ApiRequest } from '@api/basePage';

export default {
  components: {
    Upload
  },
  mixins: [brandUpdata],
  data () {
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请填写品牌名称'));
      } else {
        ApiRequest(
          '/sysback/productbrand/productbrand/getByBrandName',
          'post',
          {
            brandName: value
          },
          true
        ).then(res => {
          if (res.retStatus === '1') {
            if (
              res.retData &&
              res.retData !== 'null' &&
              res.retData.brandName
            ) {
              callback(new Error('品牌名称已存在'));
            } else {
              callback();
            }
          } else {
            callback();
          }
        });
      }
    };
    return {
      searchBrandModal: false,
      brandNameModel: '',
      linkBrandData: [],
      pageShow: 10,
      nowPage: 1,
      totalNum: 0,
      brandNameData: [],
      linkBrandCol: [
        {
          title: '品牌名称',
          key: 'brandName',
          minWidth: 120
        },
        {
          title: '厂家品牌名称',
          key: 'factoryBrandName',
          minWidth: 140
        },
        {
          title: '厂家品牌影响力',
          slot: 'factoryInfluenceMore',
          minWidth: 150
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center',
          fixed: 'right',
          minWidth: 100
        }
      ],
      serieList: [],
      newSerie: '',
      isLoading: false,
      allBrandData: [],
      requestApi: {
        // 视情况自定义
        // 新增品牌
        createProductBrand: {
          url: '/sysback/productbrand/productbrandaudit/createProductBrand', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 获取所有品牌
        getAllProductBrands: {
          url: '/sysback/productbrand/productbrand/getAllProductBrands', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 品牌放大镜
        baseQueryList: {
          url: '/sysback/productbrand/productbrand/baseQueryList',
          type: 'post'
        }
      },
      brandFormRules: {
        brandName: [
          {
            required: true,
            message: '请填写品牌名称',
            trigger: 'blur'
          },
          {
            type: 'string',
            min: 1,
            message: '品牌名称不得少于一个字符',
            trigger: 'blur'
          },
          {
            validator: validateName,
            trigger: 'blur'
          }
        ],
        brandEnName: [],
        factoryBrandEnName: [],
        factoryBrandName: [],
        imageKey2: [],
        imageKey1: [],
        imageKey3: [],
        note: [
          {
            required: true,
            message: '请填写品牌描述',
            trigger: 'change'
          },
          {
            type: 'string',
            min: 5,
            message: '品牌描述不得少于5个字符',
            trigger: 'blur'
          }
        ]
      },
      levelMap: [
        {
          value: '1',
          label: '高'
        },
        {
          value: '2',
          label: '中高'
        },
        {
          value: '3',
          label: '中'
        },
        {
          value: '4',
          label: '中低'
        },
        {
          value: '5',
          label: '低'
        }
      ]
    };
  },
  methods: {
    brandChangeBlurFun () {},
    // 品牌列表
    searchBrandFun () {
      this.searchBrandModal = true;
      let searchParam = [];
      searchParam.push({ name: 'brandName', value: this.brandNameModel });
      searchParam.push({ name: 'brandName_q', value: 'Like' });
      let data = {
        nowPage: this.nowPage,
        pageShow: this.pageShow,
        searchParam: JSON.stringify(searchParam),
        sortType: 'desc'
      };
      // 开始请求列表
      ApiRequest(
        this.requestApi.baseQueryList.url,
        this.requestApi.baseQueryList.type,
        data
      ).then(res => {
        if (res.retStatus === '1') {
          this.linkBrandData = res.retData.results;
          this.totalNum = res.retData.totalNum;
        }
      });
    },
    // 选择品牌
    selectBrandBt (row) {
      this.brandFormData.parentName = row.brandName;
      this.brandFormData.parentUuid = row.uuid;
      this.searchBrandModal = false;
    },
    linkBrandBt (type) {
      if (type === '0') {
        this.brandNameModel = '';
      }
      this.searchBrandFun();
    },
    brandChange (e) {
      this.nowPage = e;
      this.searchBrandFun();
    },
    handleBrandChange (e) {
      this.pageShow = e;
      this.searchBrandFun();
    },
    // 只能输入汉字英文数字
    keyupNative (name) {
      this.brandFormData[name] = this.brandFormData[name]
        .replace(/[\u4e00-\u9fa5]/gi, '')
        .replace(/(^\s+)|(\s+$)/g, '');
      // 不允许输入特殊符号
      this.brandFormData[name] = this.brandFormData[name]
        .replace(/[^\w\u4E00-\u9FA5]/g, '')
        .replace(/(^\s+)|(\s+$)/g, '');
    },
    // 开始请求所有品牌信息
    getAllProductBrands () {
      // this.isLoading = true;
      ApiRequest(
        this.requestApi.getAllProductBrands.url,
        this.requestApi.getAllProductBrands.type,
        {},
        false
      ).then(res => {
        if (res.retStatus === '1') {
          this.allBrandData = res.retData ? res.retData : [];
        }
        this.isLoading = false;
      });
    },
    // 删除系列
    clickSerie (index) {
      this.serieList.splice(index, 1);
    },
    // 添加系列
    addSerieList () {
      if (this.newSerie === '') {
        this.$Message.info('请输入系列!');
      } else {
        this.serieList.push(this.newSerie);
        this.newSerie = '';
      }
    },
    // 清空表单
    handleReset (name) {
      this.$router.go(-1);
    },
    maxTagPlaceholder (num) {
      return 'more ' + num;
    },
    /* 当厂家品牌影响力大于商品品牌的时候，厂家品牌名称不能为空 */
    judgeBrandNameIsEmptyFn () {
      if (this.brandFormData.factoryInfluenceMore === '2') {
        return true;
      }
      if (
        !this.brandFormData.factoryBrandName &&
        !this.brandFormData.factoryBrandEnName
      ) {
        return false;
      }
      return true;
    },
    handleSubmit () {
      if (!this.judgeBrandNameIsEmptyFn()) {
        return this.$Message.warning(
          '当厂家品牌影响力大于商品品牌的时候，厂家品牌名称不能为空'
        );
      }
      this.$refs['brandForm'].validate(valid => {
        if (valid) {
          this.isLoading = true;
          this.brandFormData.series = this.serieList.join(',');
          this.brandFormData.auditState = '1';
          let { url, type } = this.requestApi.createProductBrand;
          ApiRequest(url, type, this.brandFormData, false).then(res => {
            if (res.retStatus === '1') {
              this.$Message.success('新增品牌成功!');
              this.$router.go(-1);
            }
            this.isLoading = false;
          });
        }
      });
    }
  }
};
</script>
